//
//  BaseNetManager.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2018/12/13.
//  Copyright © 2018 wangws1990. All rights reserved.
//

import UIKit

@_exported import Alamofire
@_exported import SwiftyJSON
@_exported import HandyJSON

public protocol BaseNetRequestProtocol {
    static func baseUrlString(url:String,
                              method:HTTPMethod,
                          parameters:[String:String],
                            headers:[String:String],
                          sucesss:@escaping ((_ object : JSON) ->()),
                          failure:@escaping ((_ error : String) ->()))
    
}
class BaseNetManager:BaseNetRequestProtocol {
    class func hostUrl(txcode:String)->String{
        return "https://api.zhuishushenqi.com/\(txcode)"
    }
    class func iGetUrlString(urlString:String,parameters:[String:String],sucesss:@escaping ((_ object : JSON) ->Void),failure:@escaping ((_ error : String) ->Void)){
        baseCodeUrl(urlString: urlString, method: .get, parameters: parameters, sucesss: sucesss, failure: failure);
    }
    class func iPostUrlString(urlString:String,parameters:[String:String],sucesss:@escaping ((_ object : JSON) ->Void),failure:@escaping ((_ error : String) ->Void)){
        baseCodeUrl(urlString: urlString, method: .post, parameters: parameters, sucesss: sucesss, failure: failure);
    }
    class func baseCodeUrl(urlString:String,method:HTTPMethod,parameters:[String:String],sucesss:@escaping ((_ object : JSON) ->Void),failure:@escaping ((_ error : String) ->Void)){
        BaseNetManager.baseUrlString(url: urlString, method:method, parameters: parameters, headers: [:], sucesss: { (object) in
            sucesss(object)
        }, failure: failure);
    }
    static func baseUrlString(url:String,method: HTTPMethod,parameters:[String:String],headers:[String:String],sucesss:@escaping ((_ object : JSON) ->Void),failure:@escaping ((_ error : String) ->Void)){
        let request = AF.request(url,method:method,parameters:parameters,encoding: URLEncoding.default, headers:HTTPHeaders.init(headers));
        request.responseJSON(queue: DispatchQueue.global(), options: .mutableContainers) { (respond) in
            DispatchQueue.main.async {
                if respond.response?.statusCode == 200 && respond.error == nil{
                    let json = JSON(respond.value as Any)
                    sucesss (json)
                }else{
                    failure(respond.error.debugDescription)
                }
            }
        }
        request.resume()
    }
}
class BaseNetSystem :BaseNetRequestProtocol{
    static func baseUrlString(url: String, method: HTTPMethod, parameters: [String : String], headers: [String : String], sucesss: @escaping ((JSON) -> ()), failure: @escaping ((String) -> ())){
           var url = url;
            var data: Data? = nil;
            if method.rawValue == "GET" {
                url = url + (parameters.count > 0 ? "?":"") + parames(parameters: parameters)
            }
            else if (method.rawValue == "POST"){
                if JSONSerialization.isValidJSONObject(parameters) {
                    do {
                        data = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
                    } catch  {
                        debugPrint(error)
                    }
                }
            }
            guard let path = URL(string: url) else { return failure("") }
            let session = URLSession(configuration: URLSessionConfiguration.default)
            var request = URLRequest(url: path)
            request.httpMethod = method.rawValue;
            request.timeoutInterval = 10;
            request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
            request.addValue("chrome", forHTTPHeaderField:"User-Agent")
            if let bodyData = data {
                request.httpBody = bodyData
            }
            let task  = session.dataTask(with: request) { (datas, respone, error) in
                DispatchQueue.main.async {
                    guard let json = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else { return failure(error?.localizedDescription ?? "") }
                    sucesss(JSON(json))
                }
            }
            task.resume();
        }
        class func parames(parameters:[String:String]) -> String{
            var listData : [String] = [];
            parameters.forEach { (key,value) in
                if key.count > 0 && value.count > 0{
//                    key + "=" + value
                    listData.append("\(key)=\(value)");
                }
            }
            return listData.joined(separator: "&")
        }
}
